// 导入数据库操作模块
const { mysql } = require("../../db");
const moment = require("moment");

const formatData = (results) => {
	try {
		const data = results.map(o => ({
			...o,
			create: moment(o.create).format("YYYY-MM-DD HH:mm:ss")
		}));
		return data;
	} catch (err) {
		throw err;
	}
};

exports.Info = async (req, res, table) => {
	try {
		const sqlStr = `SELECT * FROM ${table} WHERE is_delete = 0`;
		const [results] = await mysql.query(sqlStr);
		if (results.length === 0) return res.error("无文章信息！");
		const data = formatData(results);
		return res.success(data);
	} catch (err) {
		return res.error(err);
	}
};

// 文章发布
exports.Add = async (req, res, table) => {
	const { title, content, image_path } = req.body;
	const info = { title, content, image_path, creator: req.user.id };

	try {
		const sqlStr = `INSERT INTO ${table} SET ?`;
		const [results] = await mysql.query(sqlStr, [info]);
		if (results.affectedRows !== 1) return res.cc("发布失败！");
		return res.success("发布成功");
	} catch (err) {
		return res.error(err);
	}
};

// exports.Search = (req, res) => {
//     const params = req.params.value;
//     const sqlStr = `SELECT * From anime WHERE (animename LIKE ? OR c_name LIKE ? OR intro LIKE ? OR country LIKE ? OR rate LIKE ?) AND is_delete = 0`;

//     const SeletePattern = `%${params}%`;
//     const values = Array(5).fill(SeletePattern);

//     mysql.query(sqlStr, values, (err, results) => {
//         if (err) return res.cc(err);
//         if (results.length === 0) return res.cc("该文章不存在！");

//         const data = results.map(o => ({
//             ...o,
//         }));

//         res.json({
//             status: 0,
//             message: "搜索到以下文章！",
//             data
//         });
//     });
// };